<?php
namespace app\admin\controller;

use app\admin\middleware\CheckLogin;
use app\common\model\Administrator as M_User;
use app\common\validate\Administrator as V_User;
use bigDream\thinkJump\Jump;
use think\facade\Cookie;
use think\facade\Request;

/**
 * 后台登陆
 * @package app\admin\controller
 * @author jwj <jwjbjg@gmail.com>
 * @copyright jwj
 */
class Login
{
    /**
     * 登录
     * @return \think\response\Json|\think\response\View
     */
    public function index()
    {
        if (Request::isGet()) {
            return view();
        }

        $data = Request::only(['username', 'password', 'captcha']);
        $validate = (new V_User())->scene('login');
        if (!$validate->check($data)) {
            Jump::error($validate->getError());
        }

        $user = M_User::where('username', $data['username'])->find();
        if (null === $user) {
            Jump::error('用户名不存在');
        }

        if (!password_verify($data['password'], $user['password'])) {
            Jump::error('密码错误');
        }

        $token = md5($user['username'] . mt_rand(100000, 999999) . $user['password']);
        $user->save(['token' => $token]);

        $remember = Request::has('remember', 'param', true) ? null : 86400 * 15;

        Cookie::set(CheckLogin::TokenName, $user['id'] . '@' . $user['token'], $remember);

        Jump::success('登录成功', 'Index/index');
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Cookie::delete(CheckLogin::TokenName);

        Jump::success('退出登录成功', 'Login/index');
    }

    /**
     * 验证码
     * @return \think\Response
     */
    public function captcha()
    {
        return captcha(Request::param('id'));
    }
}